# coding:utf-8
'''
Created on 2019年3月11日

用于新增需求的业务处理

@author: L.Wen
'''

from __future__ import absolute_import
from celery import shared_task
import time
from SeMFSetting.Functions import nmap
from AssetManage import models
from django.contrib.auth.models import User
from NoticeManage.views import notice_add

from celery.utils.log import get_task_logger

logger = get_task_logger(__name__)
from SeMFSetting.Functions.checkip import checkip


@shared_task
def asset_port(user_id, asset_ip_list, asset_port_list):
    user = User.objects.filter(id=user_id).first()
    for item in asset_ip_list:
        asset_ip = item
        asset = models.Asset.objects.filter(asset_key=asset_ip).first()
        if asset:
            ip = asset.asset_key
            if checkip(ip):
                port_list = nmap.nmap_port(ip, asset_port_list)
                if port_list != 0:
                    for port_info in port_list.keys():
                        port = port_info
                        name = port_list[port_info].get('name')
                        product = port_list[port_info].get('product')
                        version = port_list[port_info].get('version')
                        port_get = models.Port_Info.objects.get_or_create(
                            port=port,
                            asset=asset,
                        )
                        if port_get[1]:
                            port = port_get[0]
                            port.product = product
                            port.name = name
                            port.version = version
                            port.save()
                    data_manage = {
                        'notice_title': '资产发现通知',
                        'notice_body': '您对' + ip + '的端口发现任务完成',
                        'notice_url': '/asset/user/',
                        'notice_type': 'notice',
                    }
                    notice_add(user, data_manage)
                else:
                    data_manage = {
                        'notice_title': '资产发现通知',
                        'notice_body': '您对' + ip + '的端口发现任务完成,该主机未开放端口或网络不可达',
                        'notice_url': '/asset/user/',
                        'notice_type': 'notice',
                    }
                    notice_add(user, data_manage)
            else:
                return False
        else:
            return False

    return True
